<template>
	<view class="container">
		<view class="uni-list">
			<view class="uni-list-cell uni-list-cell-pd">
				<view>输入邀请码</view>
				<view class="uni-list-cell-db"><input type="text" v-model="inviteCode" class="uni-input"
						placeholder="请输入邀请码" /></view>
			</view>
			<view class="uni-list-cell uni-list-cell-pd">
				<view>姓名</view>
				<view class="uni-list-cell-db"><input v-model="userName" type="text" class="uni-input"
						placeholder="请输入" /></view>
			</view>
			<view class="uni-list-cell uni-list-cell-pd">
				<view>电话</view>
				<view class="uni-list-cell-db"><input v-model="contactPhone" type="text" class="uni-input"
						placeholder="请输入" /></view>
			</view>
			<view class="uni-list-cell uni-list-cell-pd">
				<view>公司名称</view>
				<view class="uni-list-cell-db"><input type="text" class="uni-input" v-model="storeName"
						placeholder="请输入" /></view>
			</view>
			<view class="uni-list-cell uni-list-cell-pd">
				<view>公司所在地区</view>
				<view class="uni-list-cell-db" @click="show = !show">
					<u-picker :show="show" ref="uPicker" :loading="loading" :columns="columns" keyName="areaName"
						@change="changeHandler" itemHeight="88" @confirm="confirm">
					</u-picker>
					<view class="uni-input" type="text" style="padding: 15rpx 0;">{{citystr}}</view>
				</view>
				<view class="uni-navigate-right"></view>
			</view>
			<view class="uni-list-cell uni-list-cell-pd">
				<view>公司详细地址</view>
				<view class="uni-list-cell-db"><input type="text" v-model="address" class="uni-input"
						placeholder="请输入详细地址" /></view>
			</view>
			<view class="uni-list-cell uni-list-cell-pd">
				<view>公司店铺照片</view>
				<view class="pic">
					<image class="display-image" :src="userInfo.physicalStoreUrl" />
				</view>
			</view>
			<!-- 			<view class="uni-list-cell uni-list-cell-pd">
				<view>选择供应商</view>
				<view class="uni-list-cell-db">
					<picker mode="selector" :range="inviteList" :value="selectedIndex" @change="onPickerChange">
						<view class="uni-input" v-if="inviteList.length > 0">
							{{inviteCode||inviteList[0]}}
						</view>
					</picker>
					<view class="uni-navigate-right"></view>
				</view>
			</view> -->

		</view>

		<view class="uni-list">
			<view class="uni-list-cell uni-list-cell-pd">
				<view class="uni-list-cell-db">
					<view class="p">公司店铺照片(上传会覆盖原图片)</view>
					<u-upload :fileList="storeList" @afterRead="afterRead" @delete="deletePic" name="storeList" multiple
						:maxCount="maxCount" :width="218" :height="218" :accept="accept"></u-upload>
				</view>
			</view>
		</view>
		<view class="uni-list">
			<view class="uni-list-cell uni-list-cell-pd">
				<view class="uni-list-cell-db">
					<view class="p">公司营业执照</view>
					<u-upload :fileList="certificateList" @afterRead="afterRead" @delete="deletePic"
						name="certificateList" multiple :maxCount="maxCount" :width="218" :height="218"
						:accept="accept"></u-upload>
				</view>
			</view>
		</view>

		<view class="text">
			本程序仅限汽车或市场门店使用，请提供门店从业者有效证明
		</view>
		<view class="bottom">
			<u-button color="#06A972" text="提交" :disabled="disabled" @click="createOrder"></u-button>
		</view>

	</view>
</template>


<script>
	var QQMapWX = require('../../../utils/qqmap-wx-jssdk.js');
	var qqmapsdk;
	import {
		getAreaList
	} from '@/api/userAddr.js';
	import {
		saveInvite,
		getUserInfo
	} from '@/api/user.js';
	import {
		HTTP_REQUEST_URL
	} from '@/config/app';
	import {
		mapState,
		mapGetters
	} from "vuex";
	import {
		paymentOrder,
		xcxPay,
		cancelPayment
	} from "@/api/payment.js";
	export default {
		data() {
			return {
				disabled: false,
				inviteList: [], // 存放批发商手机号的列表
				show: false,
				loading: false,
				columns: [
					[],
					[],
					[]
				],
				provinceList: [],
				cityList: [],
				areaList: [],
				defaultProvince: 110000, //北京市
				defaultCity: 110100, //北京市
				citystr: '请选择所在地区',
				provinceCode: 0,
				cityCode: 0,
				districtCode: 0,
				address: '',
				latitude: 0,
				longitude: 0,
				storeName: '',
				userName: '',
				contactPhone: '',
				inviteCode: '',
				storeList: [],
				certificateList: [],
				maxCount: 1,
				accept: 'image',
				defaultPhone: '18924101000', // 默认上游批发商手机号
				province: '',
				city: '',
				area: '',
				userInfo: [],
			}

		},
		computed: {
			...mapGetters({
				isLogin: 'isLogin',
				uid: 'uid',
				isStore: 'isStore',
				userType: 'userType'
			})
		},
		onLoad() {
			qqmapsdk = new QQMapWX({
				key: 'TNABZ-LWUCW-VT2RC-3XZY6-2N5LT-NIFGJ'
			});
			/**
			 * 获取默认地址、分类
			 */
			let that = this;
			that.defaultAddress();
			that.getUserInfo();
		},
		methods: {
			/**
			 * 创建订单
			 */
			async createOrder() {
				let that = this;
				let orderId = 0;
			
				that.$store.commit('IS_STORE', true);
				if (!that.userName) return that.$util.Tips({
					title: '请输入名称'
				});
				if (!that.contactPhone) return that.$util.Tips({
					title: '请输入手机号'
				});
				if (!/^1(3|4|5|7|8|9|6)\d{9}$/i.test(that.contactPhone)) return that.$util.Tips({
					title: '请输入正确的手机号码'
				});
				if (!that.storeName) return that.$util.Tips({
					title: '请输入公司名称'
				});
				
				if (!that.address) return that.$util.Tips({
					title: '请输入详细地址'
				})
				
				if (!that.provinceCode) return that.$util.Tips({
					title: '请选择公司地址'
				})
				
				if (that.storeList.length < 1) {
					return that.$util.Tips({
						title: '请上传店铺照片'
					})
				}
				if (that.certificateList.length < 1) {
					return that.$util.Tips({
						title: '请上传营业执照'
					})
				}
				if (!that.inviteCode) {
					that.show = false;
					return that.$util.Tips({
						title: '请输入邀请码'
					});
				}
				uni.showLoading({
					mask: true
				});
				that.disabled = true;
				// #ifdef MP
				uni.showLoading({
					title: '订单支付中'
				});
				orderId = await that.paymentOrder();
				// 微信支付
				that.payment(orderId);
				// #endif
			},
			paymentOrder(){
				let that = this;
				return new Promise((resolve, reject) => {
					paymentOrder({
						userInfoId: that.uid,
						inviteCode: that.inviteCode
					}).then(res => {
						resolve(res.value);
					}).catch(err => {
						uni.hideLoading();
						that.disabled = false;
						that.$util.Tips({
							title: err
						});
					});
				})
			},
			/**
			 * 支付
			 * @param {Object} orderId
			 */
			payment(paymentId) {
				let that = this;
				xcxPay({
					paymentId: paymentId,
					userInfoId: that.$store.state.app.uid,
				}).then(res => {
					let goPages = '/pages/user/index';
					let jsConfig = res.value.param;
					// #ifdef MP
					uni.requestPayment({
						timeStamp: jsConfig.timeStamp,
						nonceStr: jsConfig.nonceStr,
						package: jsConfig.package,
						signType: jsConfig.signType,
						paySign: jsConfig.paySign,
						success: function(res) {
							uni.hideLoading();
							//更新数据库
							that.applyStore();
							//修改门店身份
							that.$store.commit('USER_TYPE', 'STORE');
							return that.$util.Tips({
								title: '支付成功',
								icon: 'success'
							}, {
								tab: 5,
								url: goPages
							});
						},
						fail: function(e) {
							console.log("取消支付");
							// 调用后端接口，更新订单状态为待支付
							cancelPayment({
								orderId: paymentId
							}).then(res =>{
								// that.$util.Tips({
								// 	title: res.message
								// });
							})
							that.disabled = false;
							uni.hideLoading();
							return that.$util.Tips({
								title: '取消支付'
							}, {
								tab: 5,
								url: goPages
							});
						},
						complete: function(e) {
							uni.hideLoading();
							//关闭当前页面跳转至订单状态
							if (res.errMsg == 'requestPayment:cancel') {
								return that.$util
									.Tips({
										title: '取消支付'
									}, {
										tab: 5,
										url: goPages
									});
							}
						},
					})
					// #endif
				}).catch(err => {
					that.$util.Tips({
						title: err.msg
					});
				})
			},
			/**
			 * 获取用户信息
			 */
			getUserInfo() {
				let that = this;
				getUserInfo({
					userInfoId: that.uid,
				}).then(res => {
					that.userInfo = res.value;
					console.log(that.userInfo)
					this.inviteCode = that.userInfo.frontUserPhone
					this.userName = that.userInfo.userName
					this.contactPhone = that.userInfo.contactPhone
					this.storeName = that.userInfo.storeName
					this.citystr = that.userInfo.province + " " + that.userInfo.city + " " + that.userInfo.area
					that.provinceCode = that.userInfo.provinceCode;
					that.cityCode = that.userInfo.cityCode;
					that.districtCode = that.userInfo.districtCode;
					this.address = that.userInfo.address
				}).catch(err => {
					that.$util.Tips({
						title: err
					})
				})
			},
			async getWholesalerPhone(region) {
				try {
					const res = await uni.request({
						url: HTTP_REQUEST_URL + '/api/user/getSalerPhone',
						// url: HTTP_REQUEST_URL+'/user/getSalerPhone',
						method: 'POST',
						data: {
							province: this.province,
							city: this.city,
							area: this.area
						},
					});
					console.log('res', res)

					if (res[1]?.statusCode === 200 && res[1].data.resultCode === 1) {
						// 获取手机号和用户名并合并为字符串
						this.inviteList = res[1].data.value.map(item => `${item.userName} (${item.userPhone})`);
						if (this.inviteList.length > 0) {
							this.inviteCode = res[1].data.value[0].userPhone; // 默认选第一个手机号
						}
					} else {
						this.inviteList = [this.defaultPhone]; // 如果没有批发商，使用默认手机号
						this.inviteCode = this.defaultPhone; // 设置默认手机号
						uni.showToast({
							title: '未找到指定批发商，使用默认手机号',
							icon: 'none',
						});
					}
				} catch (error) {
					this.inviteCode = this.defaultPhone; // 出现错误时也设置为默认手机号
					uni.showToast({
						title: '请求失败，已使用默认手机号',
						icon: 'none',
					});
				}
			},
			// 处理 picker 选中事件
			onPickerChange(e) {
				this.selectedIndex = e.detail.value; // 获取用户选择的索引
				const selected = this.inviteList[this.selectedIndex];
				// 提取手机号并更新 inviteCode
				this.inviteCode = selected.match(/\(([^)]+)\)/)[1]; // 正则提取括号中的手机号
			},
			/**
			 * 选择地址
			 * @param {Object} e
			 */
			changeHandler(e) {
				let that = this;
				const {
					columnIndex,
					index,
					// 微信小程序无法将picker实例传出来，只能通过ref操作
					picker = that.$refs.uPicker,
					value
				} = e
				if (columnIndex === 0) {
					that.loading = true
					// 获取市
					that.getAddress(value[columnIndex].areaId).then(res => {
						picker.setColumnValues(1, res)

						// 获取区
						that.getAddress(res[columnIndex].areaId).then(res => {
							picker.setColumnValues(2, res)
							that.loading = false
						})
					})
				}
				if (columnIndex === 1) {
					// 获取区
					that.getAddress(value[columnIndex].areaId).then(res => {
						picker.setColumnValues(2, res)
						that.loading = false
					})
				}
			},

			defaultAddress() {
				let that = this;
				// 获取所有省
				that.getAddress(1).then(res => {
					that.provinceList = res

					// 获取默认市
					that.getAddress(that.defaultProvince).then(res => {
						that.cityList = res

						// 获取默认区
						that.getAddress(that.defaultCity).then(res => {
							that.areaList = res
							that.columns = [
								[...that.provinceList],
								[...that.cityList],
								[...that.areaList]
							];
						});
					});
				});
			},

			getAddress(id) {
				return new Promise((resolve, reject) => {
					let that = this;
					getAreaList({
						parentId: id
					}).then(res => {
						resolve(res.value);
					}).catch(err => {
						that.$util.Tips({
							title: err.msg
						});
					})
				});
			},

			confirm(e) {
				console.log('confirm', e)
				let that = this;
				that.provinceCode = e.value[0].areaId;
				that.cityCode = e.value[1].areaId;
				that.districtCode = e.value[2].areaId;
				that.citystr = e.value[0].areaName + '/' + e.value[1].areaName + '/' + e.value[2].areaName;

				this.province = e.value[0].areaName;
				this.city = e.value[1].areaName;
				this.area = e.value[2].areaName;

				//this.getWholesalerPhone(); // 根据地区获取批发商手机号
				this.show = false;
			},


			applyStore() {
				let that = this;
				that.$store.commit('IS_STORE', true);
				if (!that.userName) return that.$util.Tips({
					title: '请输入名称'
				});
				if (!that.contactPhone) return that.$util.Tips({
					title: '请输入手机号'
				});
				if (!/^1(3|4|5|7|8|9|6)\d{9}$/i.test(that.contactPhone)) return that.$util.Tips({
					title: '请输入正确的手机号码'
				});
				if (!that.storeName) return that.$util.Tips({
					title: '请输入公司名称'
				});

				if (!that.address) return that.$util.Tips({
					title: '请输入详细地址'
				})

				if (!that.provinceCode) return that.$util.Tips({
					title: '请选择公司地址'
				})

				if (that.storeList.length < 1) {
					return that.$util.Tips({
						title: '请上传店铺照片'
					})
				}
				if (that.certificateList.length < 1) {
					return that.$util.Tips({
						title: '请上传营业执照'
					})
				}
				if (!that.inviteCode) {
					that.show = false;
					return that.$util.Tips({
						title: '请输入邀请码'
					});
				}
				uni.showLoading({
					mask: true
				});

				// 调用正向地理编码接口
				qqmapsdk.geocoder({
					address: this.citystr + this.address, // 地址信息
					success(res) {
						// 获取经纬度信息
						this.latitude = res.result.location.lat;
						this.longitude = res.result.location.lng;

						/**
						 * 绑定上游供应商
						 */
						saveInvite({
							userInfoId: that.$store.state.app.uid,
							inviteCode: that.inviteCode
						}).then(res => {
							that.$formdata.post('user/applyStore', {
								"latitude": this.latitude,
								"longitude": this.longitude,
								"storeName": that.storeName,
								"provinceCode": that.provinceCode,
								"cityCode": that.cityCode,
								"address": that.address,
								"districtCode": that.districtCode,
								"userInfoId": that.$store.state.app.uid,
								"userName": that.userName,
								"contactPhone": that.contactPhone,
							}, {
								"storeImageFile": that.storeList[0].url,
								"certificateImageFile": that.certificateList[0].url,
							}).then(res => {
								uni.hideLoading();
								that.$store.commit('IS_STORE', true);
								that.$util.Tips({
									title: '提交成功',
								}, {
									tab: 3
								})
							}).catch(err => {
								that.$util.Tips({
									title: err
								});
							})
							that.show = false;
							that.$util.Tips({
								title: '绑定成功'
							});
						}).catch(err => {
							that.show = false;
							that.$util.Tips({
								title: err
							});
							return;
						})
					},
					fail(err) {
						// 失败回调
						console.error(err);
					}
				});
			},

			// 删除图片
			deletePic(event) {
				this[`${event.name}`].splice(event.index, 1)
			},

			// // 新增图片
			afterRead(event) {
				let that = this;
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				that.list = [].concat(event.file)
				// that.fileListLen = that[`${event.name}`].length
				that.list.map((item) => {
					that[`${event.name}`].push({
						...item,
						status: 'success',
						message: ''
					})
				})
			},
		}
	}
</script>

<style>
	.pic {
		width: 160rpx;
		height: 160rpx;
	}

	.container .pic image {
		width: 100%;
		height: 100%;
	}

	.text {
		text-align: center;
		/* 居中对齐 */
		font-size: 24rpx;
		/* 字体变小 */
		color: #888888;
		/* 灰色字体 */
		line-height: 1.5;
		/* 行高，让文字间距更舒适 */
	}

	.uni-list::before {
		display: none;
	}

	.uni-list::after {
		left: 30rpx;
	}

	.uni-list .uni-input {
		text-align: right;
	}

	.uni-list .p {
		padding-top: 30rpx;
	}

	.title {
		font-weight: bold;
		padding-left: 30rpx;
		padding-top: 30rpx;
	}

	.container .bottom {
		z-index: 99;
		box-sizing: border-box;
		padding: 60rpx;
		padding-bottom: calc(60rpx + constant(safe-area-inset-bottom));
		padding-bottom: calc(60rpx + env(safe-area-inset-bottom));
	}

	.uni-list .uni-list-cell {
		border-bottom: 1rpx solid #f8f8f8;
		margin: 0rpx 30rpx;
		padding: 22rpx 0rpx;
	}

	.uni-navigate-right:after {
		right: 0;
	}

	.u-upload__button .u-icon__icon {
		font-size: 28px !important;
	}

	.u-upload__deletable__icon .u-icon__icon {
		font-size: 20rpx !important;
		line-height: 20rpx !important;
	}

	.u-upload__success__icon .u-icon__icon {
		font-size: 24rpx !important;
		line-height: 24rpx !important;
	}

	.u-upload__wrap view:nth-child(3n) {
		margin-right: 0rpx;
	}
</style>